Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
`object` ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types

I am using NextJS and I previously called an internal /api route to get this data using fetch(), however, I realized that for production, it won't let you use internal api calls inside getServerSideProps Therefore, I am trying to call my MongoDB database directly from getServerSideProps.

My problem is that I get the error that my posts data that I am passing as props isn't serializable: "object ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types."

I don't understand why, as it is in the form of: [object Object],[object Object],[object Object], etc. which should work when it's passed?

My code is below for reference (explanations below the code):

export async function getServerSideProps() {
    let returnID = null
    let posts = []
    let error = false
    try {
        const client = await MongoClient.connect(`mongodb+srv://MYUNIQUEMONDODBCONNECTIONDATA`);
        const db = client.db();
        const postsCollection = db.collection("posts");
        const result = await postsCollection.find({}).limit(10).toArray();
        console.log("RESULT: " + result)
        client.close();
        posts = result.map(r => {
            return {
                title: r.title,
                body: r.body,
                id: r._id,
            }
        });
        if (posts[posts.length - 1]?.id) { // make sure it's not undefined
            returnID = posts[posts.length - 1]?.id;
        }
    }
    catch (error) {
        error = true
    }
    return {
        props: {
            startingID: String(returnID),
            startingError: error,
            startingPosts: posts,
        }
    }
}

My data I receive from my database is roughly as follows: [{"title":"1","body":"1","id":"6276767ca21167f5043d3dc8"},{"title":"2","body":"2","id":"6276767fa21167f5043d3dc9"},{"title":"3","body":"3","id":"62767682a21167f5043d3dca"}, etc.] Doesn't this match the format of my posts I'm passing as props?

The line console.log("RESULT: " + result) prints: [object Object],[object Object],[object Object],[object Object], etc.

ANSWER from @jabaa: change the return to this line: startingPosts: JSON.parse(JSON.stringify(posts))

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

return {
        props: {
            startingID: String(returnID),
            startingError: error,
            startingPosts: JSON.parse(JSON.stringify(posts)),
        }
    }

or As Chris mentioned you can use .lean() method.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda